package org.joshluisaac.servlet.filters;

import java.io.IOException;
import java.util.Date;
 
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
 
public class LogFilter implements Filter {
 
    public void doFilter(ServletRequest req, ServletResponse res,
            FilterChain chain) throws IOException, ServletException {
 
        HttpServletRequest request = (HttpServletRequest) req;
         
        //Get the IP address of client machine.
        String ipAddress = request.getRemoteAddr();
         
        //Log the IP address and current timestamp.
        System.out.println("IP "+ipAddress + ", Time "
                            + new Date().toString());
         
        chain.doFilter(req, res);
    }
    
    /**
     * In this filter example, we have implemented an interface javax.servlet.Filter 
     * and override its methods init, doFilter and destroy.The init() method is used to initialize any code that is used by Filter.
     *  Also note that, init() method will get an object of FilterConfig 
     *  which contains different Filter level information as well as init parameters which is 
     *  passed from Web.xml (Deployment descriptor).
     * 
     */
    public void init(FilterConfig config) throws ServletException {
         
        //Get init parameter
        String testParam = config.getInitParameter("test-param");

        
        //Print the init parameter
        System.out.println("Test Param: " + testParam);
    }
    public void destroy() {
        //add code to release any resource
    }
}
